/* JSPackCrx packages Chrome extension files using JavaScript.
 * http://code.google.com/p/jspackcrx
 * Copyright (C) 2011-12 gengkev.
 * 
 * This software is licensed under the terms of the GPLv3.
 * It also contains code from other projects: see /docs/licence.txt
 * See http://jspackcrx.googlecode.com/svn/LICENSE.html for details.
 */
 
/* This file automatically generates jspackcrx_include.js.
 * Run it with node (see nodejs.org) and it'll replace the
 * exising version. It takes jspackcrx.js, adds includes, and
 * compresses it. Also, be sure to install the uglify-js
 * module in order to compress code, but it'll work without.
 */

var fs  = require("fs"),
    jsp, pro, final_code;

try {
	jsp = require("uglify-js").parser,
	pro = require("uglify-js").uglify;
} catch(e) {
	jsp = pro = null;
}


// I can't believe that this works. Fast.
var jspackcrx = fs.readFileSync("jspackcrx.js","utf8");

console.log("hi");
console.time("insert-scripts");

// so awesome... replaces /* INSERT blahblahblah.js */
jspackcrx = jspackcrx.replace(/(\/\*\sINSERT\s)(.+)(\s\*\/)/gm,function(str,p1,p2,p3) {
	return fs.readFileSync(p2,"utf8"); //.replace("\ufeff","");
});

console.timeEnd("insert-scripts");

console.time("remove-comments");

// argh, replace BOM
jspackcrx = jspackcrx.replace(/\ufeff/gm,"");

// for /* */-like comments (and also /**/ [code] /**/ which removes non-build code)
jspackcrx = jspackcrx.replace(/(\/\*)([\s\S]+?)(\*\/)/gm,"");

// for //-like comments (bonus but might break stuff)
jspackcrx = jspackcrx.replace(/\/\/.*?[\n\r]+/gm,"\n");

// oh and random extra whitespace (bonus)
jspackcrx = jspackcrx.replace(/([\n\r]+\s*)/gm,"\n");
console.timeEnd("remove-comments");

fs.writeFileSync("jspackcrx_include.js",jspackcrx,"utf-8"); //redundant, in case


if (jsp !== null && pro !== null) {
try {
	console.time("uglifyjs-parse");
	var ast = jsp.parse(jspackcrx);
	console.timeEnd("uglifyjs-parse");
	
	console.time("uglifyjs-mangle");
	ast = pro.ast_mangle(ast);
	console.timeEnd("uglifyjs-mangle");
	
	console.time("uglifyjs-squeeze");
	ast = pro.ast_squeeze(ast);
	console.timeEnd("uglifyjs-squeeze");
	
	console.time("uglifyjs-compile");
	final_code = pro.gen_code(ast);
	console.timeEnd("uglifyjs-compile");
} catch(e) {
	console.log("Oh my, there's an uglify-js error: " + e);
	console.log("Cancelling compilation... though you might want to error check it :)");
	final_code = jspackcrx;
}
}
else {
	console.log("Oh no - we couldn't compile the code since uglify-js isn't available!");
	final_code = jspackcrx; //no compilation available
}

final_code = "/* Automatically generated by build.js on "+new Date()+". See it for details. */\n" + final_code;

fs.writeFileSync("jspackcrx_include.js",final_code,"utf8");
console.log("omg done!");
